package com.kotlin.lib.coroutines

import kotlinx.coroutines.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext

private fun log(content: String) {
    println("${Thread.currentThread().name}, $content")
}

fun main() = runBlocking<Unit> {
    log("1")
    val job = async (MyContinuationInterceptor()/*+Dispatchers.IO*/) {
        log("2")
        delay(200)
        log("3")
        "hello"
    }
    log("4")
    job.await()
    log("5")

    val joinToString = setOf<String>(
        "share_article/2020/09/11/EKZ1ZwD0AmL4BJ9bJD_d8b0a640@r_750w_998h-q75",
        "share_article/2020/09/11/EKZ1ZwD0AmL4BJ9bJD_3271751e@r_750w_998h-q75"
    ).joinToString()
    println(joinToString)
}

class MyContinuationInterceptor : ContinuationInterceptor {
    override val key: CoroutineContext.Key<*> = ContinuationInterceptor

    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        return MyContinuation(continuation)
    }
}

class MyContinuation<T>(val continuation: Continuation<T>) : Continuation<T> {
    override val context: CoroutineContext
        get() = continuation.context

    override fun resumeWith(result: Result<T>) {
        log("MyContinuation:resumeWith::$result")
        continuation.resumeWith(result)
    }
}